package com.zzhua.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.io.IOException;
/*MybatisConfig2
这个负责扫描com.zzhua.dao.mapper2这个包，数据源指定的使用的user2库*/

@Configuration
@MapperScan(basePackages = "com.zzhua.dao.mapper2", sqlSessionFactoryRef = "sqlSessionFactoryBean2")
public class MybatisConfig2 {

    @Bean
    public DataSource dataSource2() {
        // 设置数据源
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setUrl("jdbc:mysql://127.0.0.1/user2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
        driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("root");
        return driverManagerDataSource;
    }

    @Bean
    // 如果不配置该bean，将会抛出Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required异常
    public SqlSessionFactoryBean sqlSessionFactoryBean2(DataSource dataSource2) throws IOException { // 代码写法可参考SqlSessionFactoryBean#afterPropertiesSet

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();



        sqlSessionFactoryBean.setDataSource(dataSource2());

        // 自定义Configuration
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.getTypeAliasRegistry().registerAliases("com.zzhua.pojo");
        sqlSessionFactoryBean.setConfiguration(configuration);

        // 指定mapper.xml文件
        PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath:com/zzhua/mapper2/**.xml"));

        return sqlSessionFactoryBean; // # 之后会调用SqlSessionFactoryBean#afterPropertiesSet()方法
    }
}
